import React, {FC, Fragment, Key, useEffect, useMemo, useRef, useState} from 'react';
import "./index.less";
import HxLineCollapse from "@/components/HxLineCollapse";
import lodash from "lodash";
import dayjs from "dayjs";
import {HxArticleNormalItem} from "@/components/HxArticleItem";
import * as API from "@/services";
import {ItemType} from "rc-collapse/es/interface";
import {useRequest} from "ahooks";
import HxPagination from "@/components/HxPagination";
import {Badge, Spin} from "antd";
import {FrontAccess} from "@/services";
import classNames from "classnames";

interface FootprintProps {
}


/**
 * 访问足迹 页面
 */
const Footprint: FC<FootprintProps> = (props) => {
  const activeKeyInitialized = useRef(false);
  const [activeKey, setActiveKey] = useState<Key[]>([]);

  const dataReq = useRequest((p) => API.queryFrontAccesss({
    pageSize: 10,
    ...p,
    accessBizType: "ARTICLE"
  }))
  const data = dataReq.data?.data || [];


  const collapseItems: ItemType[] = useMemo(() => {
    const groupData = lodash.groupBy(data, (d) => {
      return dayjs(d.createTime).format("YYYY-MM");
    });

    // 获取所有月份的键并进行倒序排序
    const sortedMonths = lodash.keys(groupData).sort();

    // 按照倒序排列组合并结果
    const collapseItems = lodash.reduceRight(
      sortedMonths,
      (result: any, month) => {
        result.push({
          key: month,
          label: (
            <div className={"footprint-collapse-year-item-header"}>
              <div className={"footprint-collapse-year-item-title"}>{month}</div>
            </div>
          ),
          children: (
            <div className={`footprint-collapse-items`}>
              {groupData[month].map((item) => (
                <div className={"footprint-article-wrapper"} key={item.id}>
                  <Badge.Ribbon color={"cyan"} placement={"start"} text={dayjs(item.createTime).format("MM-DD HH:mm:ss")}>
                    <HxArticleNormalItem article={item.article as any} footprintTime={item.createTime} onArticleChange={(article) => {
                      dataReq?.mutate((oldData) => {
                        return {
                          ...oldData,
                          data: oldData!.data.map((item) => {
                            if (item.article.id === article.id) {
                              return {
                                ...item,
                                article: {
                                  ...article
                                },
                              }
                            }
                            return item;
                          })
                        } as API.RespPageResult<API.FrontAccess>;
                      })
                    }}/>
                  </Badge.Ribbon>
                  {/* <span className={"footprint-access-time"}>{dayjs(item.createTime).format("MM-DD HH:mm:ss")}</span>*/}
                </div>
              ))}
            </div>
          ),
        });
        return result;
      },
      []
    );

    return collapseItems;
  }, [data]);


  useEffect(() => {
    if (!activeKeyInitialized.current && activeKey.length == 0 && collapseItems.length > 0) {
      setActiveKey(collapseItems.map(c => c.key as string))
      activeKeyInitialized.current = true;
    }
  }, [activeKey, collapseItems]);

  return (

      <div className={classNames("footprint-container", {"footprint-container-empty": data.length === 0})}>
      <Spin spinning={dataReq.loading}>
        <HxLineCollapse
          className={"footprint-collapse"}
          activeKey={activeKey as string[]}
          onChange={v => {
            setActiveKey(v);
          }}
          ghost
          items={collapseItems}
        />
      </Spin>

      {
        dataReq.data && (
          <div className={"hx-pagination-wrapper"}>
            <HxPagination size="default"
                          total={dataReq.data?.total}
                          current={dataReq.data.current}
                          pageSize={dataReq.data.pageSize}
                          onChange={(pageNum, pageSize) => {
                            activeKeyInitialized.current = false;
                            dataReq.run({
                              page: pageNum,
                              pageSize
                            })
                          }}
            />
          </div>
        )
      }
    </div>
  );
};

export default Footprint;
